#include "stdafx.h"
#include "SaticFromBmp.h"
#include "debug_log.h"


CSaticFromBmp::CSaticFromBmp()
{
	m_hBitmap = NULL;
	m_bmpRect.SetRectEmpty();
}

CSaticFromBmp::~CSaticFromBmp()
{
	m_hBitmap = NULL;
	m_bmpRect.SetRectEmpty();
}

void CSaticFromBmp::Fresh()
{
	InvalidateRect(NULL, FALSE);
	UpdateWindow();
	ShowWindow(SW_SHOW);
}

void CSaticFromBmp::GetBmpRect(CRect *p_bmpRect)
{
	*p_bmpRect = m_bmpRect;
}

void CSaticFromBmp::SetBmpRect(const CRect bmpRect)
{
	m_bmpRect = bmpRect;
}

void CSaticFromBmp::SetBmp(HBITMAP hBitmap)
{
	m_hBitmap = hBitmap;
}

void CSaticFromBmp::SetMouseFlag(BOOL mouseFlag)
{
	m_mouseFlag = mouseFlag;
}

BOOL CSaticFromBmp::GetBitmapInfo(int *pbmpWidth, int *pbmpHeight) {
	BITMAP bitmap;
	int objRet;

	ASSERT(NULL != pbmpWidth && NULL != pbmpHeight);
	objRet = GetObject(m_hBitmap, sizeof(BITMAP), (LPSTR)&bitmap);
	if (0 == objRet) {
		LOG("GetObject() failure! %d", GetLastError());
		return FALSE;
	}		
	else {	
		//LOG("bitmap: w=%d,h=%d\n", bitmap.bmWidth, bitmap.bmHeight);
		*pbmpWidth = bitmap.bmWidth;
		*pbmpHeight = bitmap.bmHeight;
		return TRUE;
	}
}


BEGIN_MESSAGE_MAP(CSaticFromBmp, CStatic)
	ON_WM_PAINT()
	ON_WM_MOUSEMOVE()
END_MESSAGE_MAP()


BOOL CSaticFromBmp::DrawBitmap(HDC hdcDest, CRect destRect, HBITMAP hBitmap, CRect srcRect, int mode)
{   
	HDC hMemDC = NULL;
	HBITMAP hOldBitmap = NULL;

	if (NULL == hdcDest || NULL == hBitmap) 
		return FALSE;
	else {
		hMemDC = ::CreateCompatibleDC(hdcDest);
		hOldBitmap = (HBITMAP)::SelectObject(hMemDC, hBitmap);
		::SetStretchBltMode(hdcDest, COLORONCOLOR);
		::StretchBlt(hdcDest, destRect.left, destRect.top, destRect.Width(), destRect.Height(), 
			hMemDC, srcRect.left, srcRect.top, srcRect.Width(), srcRect.Height(), mode);        
		::SelectObject(hMemDC, hOldBitmap);
		::DeleteDC(hMemDC);	
		return TRUE;	
	}
}

void CSaticFromBmp::OnPaint() 
{
	CPaintDC dc(this); 
	CRect rect;
	CBrush brush;
	int bmpWidth;
	int bmpHeight;

	GetClientRect(&rect);
	if (NULL == m_hBitmap) {
		brush.CreateSolidBrush(RGB(255, 255, 255));
		dc.FillRect(&rect, &brush);
	}
	else 
	{
		if (FALSE == m_mouseFlag 
			|| (TRUE == m_mouseFlag && TRUE == m_bmpRect.IsRectEmpty())) {
			GetBitmapInfo(&bmpWidth, &bmpHeight);
			m_bmpRect.left = 0;
			m_bmpRect.top = 0;
			m_bmpRect.right = m_bmpRect.left + bmpWidth;
			m_bmpRect.bottom = m_bmpRect.top + bmpHeight;
		}
		DrawBitmap(dc, rect, m_hBitmap, m_bmpRect, SRCCOPY);
		//LOG("rect: left=%d,top=%d,w=%d,h=%d", rect.left, rect.top, rect.Width(), rect.Height());
		//LOG("bmpR: left=%d,top=%d,w=%d,h=%d", m_bmpRect.left, m_bmpRect.top, m_bmpRect.Width(), m_bmpRect.Height());
	}	
}


void CSaticFromBmp::OnMouseMove(UINT nFlags, CPoint point) 
{
	SendMessage(WM_LBUTTONDOWN,0,0);
}

